package com.meiyu.live.ui.main;

import android.os.Bundle;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v4.widget.SwipeRefreshLayout;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.android.volley.Response;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.meiyu.live.BaseActivity;
import com.meiyu.live.R;
import com.meiyu.live.net.param.IndexFilterParams;
import com.meiyu.live.net.param.MoreParams;
import com.meiyu.live.net.param.MorefilterParams;
import com.meiyu.live.net.response.HotLiveResponse;
import com.meiyu.live.net.response.MoreFilterResponse;
import com.meiyu.live.popj.LiveRoom;
import com.meiyu.live.tv.audience.AudienceActivity;
import com.meiyu.live.ui.main.widget.ColumnDetailDrawerView;
import com.meiyu.live.widget.MSGView;
import com.meiyu.live.widget.NetLoadingDailog;


/**
 * Created by zbl on 2016/8/18.
 */
public class ColumnDetailActivity extends BaseActivity implements View.OnClickListener {

    public static final String COLUMN_NAME = "column_name";
    public static final String COLUMN_ID = "column_id";

    private static final int STATE_ALL = 0;
    private static final int STATE_FILTER = 1;

    protected NetLoadingDailog dialog_loading;
    private MSGView msgView;
    private View btn_back, btn_filter;
    private TextView tv_title;
    private SwipeRefreshLayout refreshLayout;
    private ListView listView;
    private DataListAdapter adapter;
    private View footerView;
    private DrawerLayout drawerLayout;
    private ColumnDetailDrawerView columnDetailDrawerView;

    private static final int PAGE_SIZE = 12;
    private int index = 1;
    private boolean hasMore = true;
    private HotLiveResponse hotLiveResponse = new HotLiveResponse();

    private LayoutInflater inflater;
    private ImageLoader imageLoader;
    private DisplayImageOptions options;

    private String column_name;
    private long column_id;

    private int state = STATE_ALL;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_columndetail);
        init();
    }

    private void init() {
        inflater = LayoutInflater.from(this);
        imageLoader = ImageLoader.getInstance();
        options = new DisplayImageOptions.Builder()
                .showImageOnLoading(R.drawable.image_loading)          // 设置图片下载期间显示的图片
                .showImageForEmptyUri(R.drawable.image_loading)  // 设置图片Uri为空或是错误的时候显示的图片
                .showImageOnFail(R.drawable.image_loading)       // 设置图片加载或解码过程中发生错误显示的图片
                .cacheInMemory(true)                        // 设置下载的图片是否缓存在内存中
                .cacheOnDisk(true)                          // 设置下载的图片是否缓存在SD卡中
                .build();

        column_name = getIntent().getStringExtra(COLUMN_NAME);
        column_id = getIntent().getLongExtra(COLUMN_ID, 0);

        dialog_loading = new NetLoadingDailog(this);
        msgView = (MSGView) findViewById(R.id.msgView);

        drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
//        mDrawerToggle = new ActionBarDrawerToggle(this, drawerLayout, R.string.app_name, R.string.app_name) {
//            @Override
//            public void onDrawerClosed(View drawerView) {
//                super.onDrawerClosed(drawerView);
//            }
//
//            @Override
//            public void onDrawerOpened(View drawerView) {
//                super.onDrawerOpened(drawerView);
//            }
//        };
//        drawerLayout.addDrawerListener(mDrawerToggle);
        columnDetailDrawerView = (ColumnDetailDrawerView) findViewById(R.id.drawer);
        columnDetailDrawerView.setColumnId(column_id);
        columnDetailDrawerView.setFilterViewListener(new ColumnDetailDrawerView.FilterViewListener() {
            @Override
            public void onClickOk(String location, long type_id, int[] range) {
                dialog_loading.loading();
                getFilterData(location, type_id, range);
                if (drawerLayout.isDrawerOpen(GravityCompat.END)) {
                    drawerLayout.closeDrawer(GravityCompat.END);
                }
            }
        });

        tv_title = (TextView) findViewById(R.id.tv_title);
        tv_title.setText(column_name);
        btn_back = findViewById(R.id.btn_back);
        btn_back.setOnClickListener(this);
        btn_filter = findViewById(R.id.btn_filter);
        btn_filter.setOnClickListener(this);

        refreshLayout = (SwipeRefreshLayout) findViewById(R.id.swipe_container);
        refreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                getData(true);
            }
        });
        listView = (ListView) findViewById(R.id.listview);
        footerView = inflater.inflate(R.layout.view_loadmore, null);
        listView.addFooterView(footerView);
        footerView.setVisibility(View.GONE);

        adapter = new DataListAdapter();
        listView.setAdapter(adapter);
        listView.setOnScrollListener(new AbsListView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(AbsListView absListView, int scrollState) {
                if (state == STATE_ALL) {
                    if (scrollState == AbsListView.OnScrollListener.SCROLL_STATE_IDLE) { // 判断滚动到底部
                        if (absListView.getLastVisiblePosition() == (absListView.getCount() - 1) && hasMore) {
                            footerView.setVisibility(View.VISIBLE);
                            getData(false);
                        }
                    }
                }
            }

            @Override
            public void onScroll(AbsListView absListView, int i, int i1, int i2) {

            }
        });

        dialog_loading.loading();
        getData(true);
        getTypeData();
    }

    @Override
    public void onClick(View view) {
        if (view == btn_filter) {
            if (drawerLayout.isDrawerOpen(GravityCompat.END)) {
                drawerLayout.closeDrawer(GravityCompat.END);
            } else {
                drawerLayout.openDrawer(GravityCompat.END);
            }
        } else if (view == btn_back) {
            finish();
        }
    }

    @Override
    public void onBackPressed() {
        if (drawerLayout.isDrawerOpen(GravityCompat.END)) {
            drawerLayout.closeDrawer(GravityCompat.END);
        } else {
            super.onBackPressed();
        }
    }

    @Override
    public void onError() {
        dialog_loading.dismissDialog();
        refreshLayout.setRefreshing(false);
        footerView.setVisibility(View.GONE);
        super.onError();
    }

    private void getData(final boolean reload) {
        if (reload) {
            index = 1;
            hasMore = true;
        }
        int area[] = {PAGE_SIZE, index + PAGE_SIZE - 1};
        request(new MoreParams("美女", area), HotLiveResponse.class, new Response.Listener<HotLiveResponse>() {
            @Override
            public void onResponse(HotLiveResponse hotLiveResponse) {
                dialog_loading.dismissDialog();
                refreshLayout.setRefreshing(false);
                footerView.setVisibility(View.GONE);
                if (hotLiveResponse != null) {
                    if (reload) {
                        ColumnDetailActivity.this.hotLiveResponse.getHash().clear();
                    }
                    ColumnDetailActivity.this.hotLiveResponse.getHash().addAll(hotLiveResponse.getHash());
                    index += PAGE_SIZE;
                    if (hotLiveResponse.getHash().size() < PAGE_SIZE) {
                        hasMore = false;
                    }
                    adapter.notifyDataSetChanged();
                    if (hotLiveResponse.getHash().size() == 0) {
                        msgView.show_empty();
                    } else {
                        msgView.dismiss();
                    }
                } else {
                    msgView.show_error();
                }
            }
        });
    }

    private void getFilterData(String location, long type_id, int[] range) {
        long[] sl_assort_id = (type_id >= 0 ? new long[]{column_id, type_id} : new long[]{column_id});
        //如果用户未在界面选择，三个参数都有默认值，location为当前城市，
        //sl_assort_id第一位为首页选中的一级类别，第二位为当前界面选中的二级类别，如未选择，则没有第二个元素
        //rows默认值为｛1，50｝
        request(new IndexFilterParams(location, sl_assort_id, range), HotLiveResponse.class, new Response.Listener<HotLiveResponse>() {
            @Override
            public void onResponse(HotLiveResponse hotLiveResponse) {
                dialog_loading.dismissDialog();
                refreshLayout.setRefreshing(false);
                footerView.setVisibility(View.GONE);
                if (hotLiveResponse != null) {
                    ColumnDetailActivity.this.hotLiveResponse.getHash().clear();
                    ColumnDetailActivity.this.hotLiveResponse.getHash().addAll(hotLiveResponse.getHash());
                    adapter.notifyDataSetChanged();
                    if (hotLiveResponse.getHash().size() == 0) {
                        msgView.show_empty();
                    } else {
                        msgView.dismiss();
                    }
                } else {
                    msgView.show_error();
                }
            }
        });
    }

    class DataListAdapter extends BaseAdapter {

        private class ViewHolder {
            ImageView[] iv_image;
            TextView[] tv_name, tv_title, tv_count;
            View[] layout_grid;
        }

        View.OnClickListener onItemClickListener = new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                int index = (int) view.getTag();
                final LiveRoom bean = hotLiveResponse.getHash().get(index);
                AudienceActivity.start(ColumnDetailActivity.this, bean);
            }
        };

        @Override
        public int getCount() {
            return hotLiveResponse != null && hotLiveResponse.getHash() != null ? (int) Math.ceil(((float) hotLiveResponse.getHash().size()) / 2) : 0;
        }

        @Override
        public Object getItem(int position) {
            return null;
        }

        @Override
        public long getItemId(int position) {
            return 0;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            ViewHolder holder = null;
            if (convertView == null) {
                convertView = inflater.inflate(R.layout.adapter_hotlive, null);
                holder = new ViewHolder();
                holder.iv_image = new ImageView[]{
                        (ImageView) convertView.findViewById(R.id.iv_image0),
                        (ImageView) convertView.findViewById(R.id.iv_image1)
                };
                holder.tv_name = new TextView[]{
                        (TextView) convertView.findViewById(R.id.tv_name0),
                        (TextView) convertView.findViewById(R.id.tv_name1)
                };
                holder.tv_count = new TextView[]{
                        (TextView) convertView.findViewById(R.id.tv_count0),
                        (TextView) convertView.findViewById(R.id.tv_count1)
                };
                holder.tv_title = new TextView[]{
                        (TextView) convertView.findViewById(R.id.tv_title0),
                        (TextView) convertView.findViewById(R.id.tv_title1)
                };
                holder.layout_grid = new View[]{
                        convertView.findViewById(R.id.layout_grid0),
                        convertView.findViewById(R.id.layout_grid1)
                };
                holder.layout_grid[0].setOnClickListener(onItemClickListener);
                holder.layout_grid[1].setOnClickListener(onItemClickListener);
                convertView.setTag(holder);
            } else {
                holder = (ViewHolder) convertView.getTag();
            }
            for (int i = 0; i < 2; i++) {
                int index = position * 2 + i;
                holder.layout_grid[i].setTag(index);
                if (index >= hotLiveResponse.getHash().size()) {
                    holder.layout_grid[i].setVisibility(View.INVISIBLE);
                } else {
                    holder.layout_grid[i].setVisibility(View.VISIBLE);
                    final LiveRoom bean = hotLiveResponse.getHash().get(index);
                    imageLoader.displayImage(bean.getImage_url(), holder.iv_image[i], options);
                    holder.tv_title[i].setText(bean.getDescription());
                    holder.tv_name[i].setText(bean.getAnchor_name());
                    holder.tv_count[i].setText("" + bean.getViewer_num());
                }
            }
            return convertView;
        }
    }

    /**
     * 获取子类别
     */
    private void getTypeData() {
        request(new MorefilterParams(column_id), MoreFilterResponse.class, new Response.Listener<MoreFilterResponse>() {
            @Override
            public void onResponse(MoreFilterResponse moreFilterResponse) {
                if (moreFilterResponse != null) {
                    columnDetailDrawerView.setTypeData(moreFilterResponse.getHash());
                }
            }
        });
    }
}
